package com.hzit.payweb.service.impl;

import com.hzit.paycommon.paycommonapi.aliapy.AlipayPrePayReq;
import com.hzit.paycommon.paycommonapi.aliapy.resp.AlipayPrePayRespData;
import com.hzit.paycommon.paycommonapi.enums.PayWayEnum;
import com.hzit.paycommon.paycommonapi.enums.StatusEnum;
import com.hzit.paycommon.paycommonapi.resp.RespVo;
import com.hzit.payweb.factory.PayFactory;
import com.hzit.payweb.iclient.IAlipayFrontClient;
import com.hzit.payweb.model.PaySerial;
import com.hzit.payweb.service.IPaySerialService;
import com.hzit.payweb.service.IPayStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * InitializingBean  初始化bean
 * 支付宝扫码支付
 */
@Service
public class AlpayPrePayStrategyImpl implements IPayStrategy , InitializingBean {

    @Autowired
    private IAlipayFrontClient iAlipayFrontClient;

    @Autowired
    private IPaySerialService paySerialService;

    private Logger logger = LoggerFactory.getLogger(AlpayPrePayStrategyImpl.class);

    /**
     * 调用扫码支付
     * @param paySerial
     * @return
     */
    @Override
    public RespVo pay(PaySerial paySerial ) {

        //支付宝扫码支付，1.封装扫码支付的接口所需的参数
        AlipayPrePayReq alipayPaymentReq = new AlipayPrePayReq();

        //金额转换
        alipayPaymentReq.setAmount(paySerial.getAmount().toString());
        alipayPaymentReq.setNotifyUrl("http://www.baidu.com"); //TODO
        alipayPaymentReq.setReturnUrl("http://www.baidu.com");
        alipayPaymentReq.setSerialNum(paySerial.getPaySerialNo());
        alipayPaymentReq.setSubject(paySerial.getSubject());

        //2.通过fegin调用 支付宝前置服务中 扫码支付接口
        RespVo<AlipayPrePayRespData> resp = iAlipayFrontClient.tradePre(alipayPaymentReq);
        logger.info("支付前置服务返回内容：{}",resp);

        // 3.更新流水为支付中
        if(0 == resp.getCode()){
            paySerialService.updatePaySerialStatus(paySerial.getPaySerialNo(), StatusEnum.PAYING.getCode());
            return  resp;

        }

        //封装返回
        RespVo resp1 = new RespVo();
        resp1.setCode(-1);
        resp1.setMsg("调用失败");
        return resp1;

    }

    /**
     * 容器启动的时候就会执行
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        logger.info("初始化AlpayPrePayStrategyImpl对象放入map中....");
        /**
         * this 当前实例对象
         */
        PayFactory.map.put(PayWayEnum.alipay_trade_precreate.getCode(),this);
    }
}
